import NextImage  from 'next/image'
import { useEffect, useState } from 'react'
import LoadingIcon from '../assets/icon/loading.svg'

export default function PageLoading () {
  const [isLoading, setIsLoading] = useState(true)
  const imgList = [
    '/images/loading/loading-01.png',
    '/images/loading/loading-02.png',
    '/images/loading/loading-03.png',
    '/images/loading/loading-04.png',
    '/images/loading/loading-05.png',
    '/images/loading/loading-06.png',
    '/images/loading/loading-07.png',
    '/images/loading/loading-08.png',
    '/images/loading/loading-09.png',
    '/images/loading/loading-10.png',
    '/images/loading/loading-11.png',
    '/images/loading/loading-12.png',
  ]

  const [imgUrl, setImgUrl] = useState('/images/loading/loading-01.png')

  const getAsyncAssets = async () => {
    return new Promise((resolve) => {
      const list = []
      let start = 1
      let end = 12
      for (let i = start; i <= end; i++) {
        const img = new Image()
        img.src = `/images/loading/loading-${i.toString().padStart(2, '0')}.png`
        list.push(img)
        img.onload = () => {
          if (i === end) {
            resolve(list)
          }
        }
      }
    })
  }
  useEffect(() => {
    (async () => {
      await getAsyncAssets()
      let index = 0
      let times = 0
      let timer = setInterval(() => {
        if (times < 20) {
          times++
          index = index === 11 ? 0 : index + 1
          setImgUrl(imgList[index])
        } else {
          clearInterval(timer)
          setIsLoading(false)
        }
      }, 100)
    })()
    return () => {
    }
  }, [])

  return (
    <>
      {isLoading && (
        <div className="fixed top-0 left-0 w-screen h-screen z-[100] bg-[#D6C9C1] flex flex-col items-center justify-center">
          <NextImage className='md:w-[200px] mb-[20vh]' width={200} height={200} src={imgUrl} alt="" />
          <LoadingIcon className="absolute bottom-[10vh] text-[50px] md:text-[140px] animate-spin"/>
        </div>
      )}
    </>
  )
}
